﻿using CommunityToolkit.Mvvm.Messaging;
using machine_registration.Helpers;
using machine_registration.Models;
using machine_registration.Views.Pages;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Wpf.Ui;
using Application=System.Windows.Application;
using static System.Net.Mime.MediaTypeNames;
namespace machine_registration.ViewModels
{
    /// <summary>
    /// 借出设备数据查询
    /// </summary>
    public partial class LoanRecordPageViewModel : ViewModel
    {
        private readonly AppDbContext _db;
        /// <summary>
        ///  借出设备数据数据源集合
        /// </summary>
        [ObservableProperty]
        public ObservableCollection<BorrowRecord> _LoanRecordPageRecords=new();
        /// <summary>
        /// 选择的项
        /// </summary>
        [ObservableProperty]
        public BorrowRecord _SelectedRecord;
        [ObservableProperty]
        private int _currentPage = 1;
        [ObservableProperty]
        private string _SearchKeyword;
        [ObservableProperty]
        public List<string> _SearchKeyword_list = new();
        [ObservableProperty]
        private int _pageSize = 10;
        [ObservableProperty]
        private List<int> _pageSize_list = new() { 10, 20, 50, 100 };
        [ObservableProperty]
        public int _TotalCount;
        /// <summary>
        /// 设备类型选项
        /// </summary>
        public List<DeviceTypeOption> DeviceTypes { get; } = Enum.GetValues(typeof(DeviceType))
            .Cast<DeviceType>()
            .Select(t => new DeviceTypeOption(t))
            .ToList();
        /// <summary>
        /// 设备状态选项
        /// </summary>
        public List<DeviceInventoryStatus> DeviceStatus { get; } = Enum.GetValues(typeof(InventoryStatus))
            .Cast<InventoryStatus>()
            .Select(t => new DeviceInventoryStatus(t))
            .ToList();
        #region 搜索页面查询字段
        // 新增筛选属性
        [ObservableProperty]
        private DeviceType? _selectedDeviceType;
        [ObservableProperty]
        private InventoryStatus? _selectedStatus;
        [ObservableProperty]
        private bool _includeRetired;
        /// <summary>
        /// 借出日期
        /// </summary>
        [ObservableProperty]
        private DateTime? _BorrowDate;
        /// <summary>
        /// 预计归还日期
        /// </summary>
        [ObservableProperty]
        private DateTime? _ExpectedReturnDate;
        /// <summary>
        /// 对方信息  当前责任人（借用人）
        /// </summary>
        [ObservableProperty]
        private string _CurrentKeeper = string.Empty;
        /// <summary>
        /// 对方信息  当前责任人列表
        /// </summary>
        [ObservableProperty]
        public List<string> _CurrentKeeper_list = new();
        /// <summary>
        /// 来源编号 
        /// </summary>
        [ObservableProperty]
        public string? _SourceNumber;
        /// <summary>
        /// 任务名称相关信息 
        /// </summary>
        [ObservableProperty]
        public string? _TaskName;
        #endregion
        [ObservableProperty]
        private bool _HasPreviousPage;
        [ObservableProperty]
        private bool _HasNextPage;
        // 修改分页属性计算
        public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
        // 设备状态选项选项模型
        public class DeviceInventoryStatus
        {
            public InventoryStatus Value { get; }
            public string Description { get; }

            public DeviceInventoryStatus(InventoryStatus type)
            {
                Value = type;
                Description = type.GetDescription();
            }
        }
        // 命令系统 
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }   
        public LoanRecordPageViewModel(AppDbContext dbContext, INavigationService _navigationService)
        {

            _db = dbContext;
            navigationService = _navigationService;

            // 命令初始化 

            // 初始化时加载第一页数据 
            //  LoadPagedDataAsync().ConfigureAwait(false);

            // 命令初始化（增加执行条件判断）
            // 命令初始化 
            PreviousPageCommand = new RelayCommand(
                execute: () =>
                {
                    CurrentPage--;  // 页码递减
                                    // 注意：此处不需要手动调用 LoadPagedDataAsync，因为 CurrentPage 变更会自动触发
                },
                canExecute: () => HasPreviousPage  // 绑定到最新状态
            );

            NextPageCommand = new RelayCommand(
                execute: () =>
                {
                    CurrentPage++;  // 页码递增
                                    // 注意：此处不需要手动调用 LoadPagedDataAsync，因为 CurrentPage 变更会自动触发
                },
                canExecute: () => HasNextPage  // 绑定到最新状态
            );



        }
        public override void OnNavigatedTo()
        {
            //每次导航成功 都要刷新数据一次
            //每次导航成功 都要刷新数据一次
            LoadPagedDataAsync().ConfigureAwait(false);
            // 加载责任人列表
            LoadCurrentKeepersAsync().ConfigureAwait(false);
            LoadDeviceNameAsync().ConfigureAwait(false);

        }
        private INavigationService? navigationService;
        [RelayCommand]
        private async void Search()
        {
            CurrentPage = 1; // 重置到第一页
            await LoadPagedDataAsync().ConfigureAwait(false);
            // 在UI线程检查结果
            if (TotalCount == 0)
            {
                await System.Windows.Application.Current.Dispatcher.Invoke(async () =>
                {
                    await ShowDialog("搜索提示", "没有找到符合条件的设备记录");
                });
            }



        }
        // 重置搜索条件命令
        [RelayCommand]
        private void ResetSearch()
        {
            SearchKeyword = string.Empty;
            SelectedDeviceType = null;
            SelectedStatus = null;
            IncludeRetired = false;
      
            SourceNumber = null;
            TaskName = null;
            CurrentKeeper = null;

            LoadPagedDataAsync().ConfigureAwait(false);
        }
        /// <summary>
        /// 归还设备按钮
        /// </summary>
      
        [RelayCommand]
        private async void GiveBack()
        {
            if (SelectedRecord == null) return;

            try
            {
                // ✅ 步骤1：更新借出记录状态
                SelectedRecord.Status = InventoryStatus.Completed;
                SelectedRecord.ActualReturnDate = DateTime.Now;
                SelectedRecord.UpdatedAt = DateTime.Now;
                SelectedRecord.IsSelected = false;
                // ✅ 步骤2：查找关联的设备库存记录（通过 MachineId）
                var deviceInventory = await _db.DeviceInventorys
                    .FirstOrDefaultAsync(d => d.MachineId == SelectedRecord.MachineId);

                if (deviceInventory == null)
                {
                    await ShowDialog("错误", "未找到对应的设备库存记录");
                    return;
                }

                // ✅ 步骤3：更新设备库存状态
                deviceInventory.Status = InventoryStatus.InStock; // 恢复为在库可借
                deviceInventory.CurrentKeeper = null; // 清除当前责任人

                // ✅ 步骤4：在事务中保存所有变更
                using (var transaction = await _db.Database.BeginTransactionAsync())
                {
                    try
                    {
                        // 附加并标记借出记录为修改状态
                        _db.Attach(SelectedRecord);
                        _db.Entry(SelectedRecord).State = EntityState.Modified;

                        // 附加并标记库存记录为修改状态
                        _db.Attach(deviceInventory);
                        _db.Entry(deviceInventory).State = EntityState.Modified;

                        await _db.SaveChangesAsync();
                        await transaction.CommitAsync();

                        await ShowDialog("成功", "设备归还完成，库存状态已更新");
                    }
                    catch
                    {
                        await transaction.RollbackAsync();
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                await ShowDialog("错误", $"操作失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 生成借出信息
        /// </summary>
        [RelayCommand]
        private void Information()
        {
        
            List<BorrowRecord> borrowRecords= GetSelectedRecords().Where(x => x.Status == InventoryStatus.Pending).ToList(); ;
            if (SelectedRecord != null&& borrowRecords.Count==0)
            {
                //获取名称
                var name = SelectedRecord.Counterpart;
                var deviceName = SelectedRecord.DeviceName;
                var sn = SelectedRecord.MachineId;
                var Status = SelectedRecord.Status.GetDescription();
                // var OwnerId= SelectedRecord.OwnerId;
                var text = $"设备名称：{deviceName}\n设备SN：{sn} \n借用人：{name}  \n当前状态: {Status}";
                Clipboard.SetText(text);
            }else 
            {
                var text_list = "";
                var count_str = $"共有{borrowRecords.Count}台设备未还,未还信息设备如下: \n";
                text_list+= count_str;
                int i = 0;
                foreach (var item in borrowRecords)
                {
                    i++;
                    //获取名称
                    var name = item.Counterpart;
                    var deviceName = item.DeviceName;
                    var sn = item.MachineId;
                    var type=item.DeviceType.GetDescription();
                    var Status = item.Status.GetDescription();
                    var ExpectedReturnDate = item.ExpectedReturnDate?.ToString("yyyy-MM-dd"); ;
                    // var OwnerId= SelectedRecord.OwnerId;
                    var text = $"\n序号: {i.ToString()} 待还机信息如下: \n设备名称：{deviceName}\n设备类型：{type}\n设备SN：{sn} \n借用人：{name}  \n当前状态: {Status}\n预计归还日期: {ExpectedReturnDate}\n";
                    text_list+=text;
                 
                }
                text_list += "\n注意：以上信息用于记录借还机，如已还机必须要有还机信息，如有疑问请及时咨询！";
                Clipboard.SetText(text_list);
            }
       
        }
        /// <summary>
        /// 生成归还信息
        /// </summary>
        [RelayCommand]
        private void GiveBackInformation()
        {
          
            List<BorrowRecord> borrowRecords = GetSelectedRecords().Where(x=>x.Status==InventoryStatus.Completed).ToList();
            if (SelectedRecord != null && borrowRecords.Count == 0)
            {
                //获取名称
                var name = SelectedRecord.Counterpart;
                var deviceName = SelectedRecord.DeviceName;
                var sn = SelectedRecord.MachineId;
                var Status = SelectedRecord.Status.GetDescription();
                // var OwnerId= SelectedRecord.OwnerId;
                var text = $"设备名称：{deviceName}\n设备SN：{sn} \n借用人：{name}  \n当前状态: {Status}";
                Clipboard.SetText(text);
            }
            else
            {
                var text_list = "";
                var count_str = $"共有{borrowRecords.Count}台设备已还,已还信息设备如下: \n";
                text_list += count_str;
                int i = 0;
                foreach (var item in borrowRecords)
                {
                    i++;
                    //获取名称
                    var name = item.Counterpart;
                    var deviceName = item.DeviceName;
                    var sn = item.MachineId;
                    var type = item.DeviceType.GetDescription();
                    var Status = item.Status.GetDescription();
                    var ExpectedReturnDate = item.ExpectedReturnDate?.ToString("yyyy-MM-dd"); ;
                    // var OwnerId= SelectedRecord.OwnerId;
                    var text = $"\n序号: {i.ToString()} 待还机信息如下: \n设备名称：{deviceName}\n设备类型：{type}\n设备SN：{sn} \n借用人：{name}  \n当前状态: {Status}\n预计归还日期: {ExpectedReturnDate}\n";
                    text_list += text;

                }
                text_list += "\n注意：以上信息用于记录借还机，如已还机必须要有还机信息，如有疑问请及时咨询！";
                Clipboard.SetText(text_list);
            }

        }
        
        // 获取所有勾选的项
        public List<BorrowRecord> GetSelectedRecords()
        {
            return LoanRecordPageRecords
                .Where(record => record.IsSelected==true)
                .ToList();
        }
        private async void DeleteRecord()
        {

        }
        private async Task ShowDialog(string title, string content)
        {
            var dialog = new Wpf.Ui.Controls.MessageBox
            {
                Title = title,
                Content = content,
                CloseButtonText = "我已知晓"
            };
            await dialog.ShowDialogAsync();
        }
        // 增加属性变更处理 
        partial void OnCurrentPageChanged(int value)
        {
            // 触发分页数据刷新 
            LoadPagedDataAsync().ConfigureAwait(false);
            // 更新命令可用状态 
            (PreviousPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
        }
        partial void OnPageSizeChanged(int value)
        {
            // 页数变化时重置到第一页 
            CurrentPage = 1;
            LoadPagedDataAsync().ConfigureAwait(false);
        }
        public async Task LoadPagedDataAsync()
        {
            try
            {

                var query = BuildQuery(); // 提取查询构建逻辑

                // 总数查询（必须使用相同的查询条件）
                TotalCount = await query.CountAsync();

                // 分页查询
                var data = await query
                    .Skip((CurrentPage - 1) * PageSize)
                    .Take(PageSize)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    LoanRecordPageRecords.Clear();
                    foreach (var record in data)
                    {
                        LoanRecordPageRecords.Add(record);
                    }
                    UpdatePaginationState(); // 更新按钮状态
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"分页加载失败: {ex.Message}");
                // 实际项目中应添加错误处理逻辑 
            }
        }
        /// <summary>
        /// 加载当前责任人列表
        /// </summary>
        /// <returns></returns>
        private async Task LoadCurrentKeepersAsync()
        {
            try
            {
                var keepers = await _db.DeviceInventorys
                    .Where(d => !string.IsNullOrEmpty(d.CurrentKeeper))
                    .Select(d => d.CurrentKeeper)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    CurrentKeeper_list.Clear();
                    foreach (var keeper in keepers)
                    {
                        CurrentKeeper_list.Add(keeper);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载责任人列表失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 加载设备名称列表绑定
        /// </summary>
        /// <returns></returns>
        private async Task LoadDeviceNameAsync()
        {
            try
            {
                var keepers = await _db.BorrowRecords
                    .Where(d => !string.IsNullOrEmpty(d.DeviceName))
                    .Select(d => d.DeviceName)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    SearchKeyword_list.Clear();
                    foreach (var keeper in keepers)
                    {
                        SearchKeyword_list.Add(keeper);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载设备名称列表失败: {ex.Message}");
            }
        }
        // 提取查询条件构建方法
        private IQueryable<BorrowRecord> BuildQuery()
        {
            var query = _db.BorrowRecords
                .AsNoTracking()
                .OrderByDescending(r => r.BorrowDate)
                .AsQueryable();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(SearchKeyword))
            {
                query = query.Where(d =>
                    d.DeviceName.Contains(SearchKeyword) ||
                    d.MachineId.Contains(SearchKeyword) ||
                    d.SerialNumber.Contains(SearchKeyword));
            }

            if (SelectedDeviceType.HasValue)
            {
                query = query.Where(d => d.DeviceType == SelectedDeviceType.Value);
            }

            if (SelectedStatus.HasValue)
            {
                query = query.Where(d => d.Status == SelectedStatus.Value);
            }

            if (BorrowDate.HasValue)
            {
                query = query.Where(d => d.BorrowDate >= BorrowDate.Value);
            }

            if (ExpectedReturnDate.HasValue)
            {
                query = query.Where(d => d.ExpectedReturnDate <= ExpectedReturnDate.Value.AddDays(1));
            }
      
            // 添加当前责任人筛选
            if (!string.IsNullOrWhiteSpace(CurrentKeeper))
            {
                query = query.Where(d => d.Counterpart == CurrentKeeper);
            }

            return query;
        }
        // 更新分页状态
        private void UpdatePaginationState()
        {
            HasPreviousPage = CurrentPage > 1;
            HasNextPage = CurrentPage < TotalPages;


            // 强制刷新命令状态
            (PreviousPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
        }
    }
}
